package org.jeecg.modules.controlStrategy.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.controlStrategy.entity.ControlStrategy;
import org.jeecg.modules.controlStrategy.service.IControlStrategyService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.enterpriseBasicInformation.entity.EnterpriseBasicInformation;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 一厂一策管理
 * @Author: jeecg-boot
 * @Date:   2024-04-10
 * @Version: V1.0
 */
@Api(tags="一厂一策管理")
@RestController
@RequestMapping("/controlStrategy/controlStrategy")
@Slf4j
public class ControlStrategyController extends JeecgController<ControlStrategy, IControlStrategyService> {
	@Autowired
	private IControlStrategyService controlStrategyService;
	 @Autowired
	 private ISysDepartService sysDepartService;
	/**
	 * 分页列表查询
	 *
	 * @param controlStrategy
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "一厂一策管理-分页列表查询")
	@ApiOperation(value="一厂一策管理-分页列表查询", notes="一厂一策管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ControlStrategy controlStrategy,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ControlStrategy> queryWrapper = QueryGenerator.initQueryWrapper(controlStrategy, req.getParameterMap());

		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String username=loginUser.getUsername();
		if(!username.equals("admin")){
			List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
			List<String> departNames = sysDeparts.stream()
					.filter(item -> item.getOrgType().equals("1"))
					.map(SysDepart::getDepartName)
					.collect(Collectors.toList());
			if(departNames==null||departNames.size()==0){
				return Result.error("未找到公司信息，请联系管理员");
			}
			queryWrapper.eq("company_name", departNames.get(0));
		}

		Page<ControlStrategy> page = new Page<ControlStrategy>(pageNo, pageSize);
		IPage<ControlStrategy> pageList = controlStrategyService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @AutoLog(value = "一厂一策管理-列表查询")
	 @ApiOperation(value="一厂一策管理-列表查询", notes="一厂一策管理-列表查询")
	 @GetMapping(value = "/listOne")
	 public Result<?> queryPageListOne() {

		 LambdaQueryWrapper<ControlStrategy> lqw = Wrappers.lambdaQuery(ControlStrategy.class);
		 LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String username=loginUser.getUsername();

		 if(!username.equals("admin")){
			 List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
			 List<String> departNames = sysDeparts.stream()
					 .filter(item -> item.getOrgType().equals("1"))
					 .map(SysDepart::getDepartName)
					 .collect(Collectors.toList());
			 if(departNames==null||departNames.size()==0){
				 return Result.error("未找到公司信息，请联系管理员");
			 }
			 lqw.eq(ControlStrategy::getCompanyName, departNames.get(0));
		 }

		 lqw.orderByDesc(ControlStrategy::getCreateTime);
		 ControlStrategy one = controlStrategyService.getOne(lqw);
		 if (Objects.isNull(one)){
			 one = new ControlStrategy();
			 one.setCompanyName(username);
			 one.setCreateTime(new Date());
			 controlStrategyService.save(one);
		 }
		 return Result.OK(one);
	 }


	 @AutoLog(value = "一厂一策管理-对外-列表查询")
	 @ApiOperation(value="一厂一策管理-对外-列表查询", notes="一厂一策管理-对外-列表查询")
	 @GetMapping(value = "/m/listOne")
	 public Result<?> queryPageListOne2(@RequestParam(name="companyName") String companyName) {
		 LambdaQueryWrapper<ControlStrategy> lqw = Wrappers.lambdaQuery(ControlStrategy.class);
		 /*LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String username=loginUser.getUsername();

		 if(!username.equals("admin")){
			 List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
			 List<String> departNames = sysDeparts.stream()
					 .filter(item -> item.getOrgType().equals("1"))
					 .map(SysDepart::getDepartName)
					 .collect(Collectors.toList());
			 if(departNames==null||departNames.size()==0){
				 return Result.error("未找到公司信息，请联系管理员");
			 }
			 lqw.eq(ControlStrategy::getCompanyName, departNames.get(0));
		 }*/
		 lqw.eq(ControlStrategy::getCompanyName, companyName);
		 lqw.orderByDesc(ControlStrategy::getCreateTime);
		 ControlStrategy one = controlStrategyService.getOne(lqw);
		 if (Objects.isNull(one)){
			 one = new ControlStrategy();
			 one.setCompanyName(companyName);
			 one.setCreateTime(new Date());
			 controlStrategyService.save(one);
		 }
		 return Result.OK(one);
	 }

	 /**
	 *   添加
	 *
	 * @param controlStrategy
	 * @return
	 */
	@AutoLog(value = "一厂一策管理-添加")
	@ApiOperation(value="一厂一策管理-添加", notes="一厂一策管理-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ControlStrategy controlStrategy) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String username=loginUser.getUsername();

		if(!username.equals("admin")){
			List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
			List<String> departNames = sysDeparts.stream()
					.filter(item -> item.getOrgType().equals("1"))
					.map(SysDepart::getDepartName)
					.collect(Collectors.toList());
			if(departNames==null||departNames.size()==0){
				return Result.error("未找到公司信息，请联系管理员");
			}
			controlStrategy.setCompanyName(departNames.get(0));
		}else {
			controlStrategy.setCompanyName(username);
		}
		controlStrategyService.save(controlStrategy);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param controlStrategy
	 * @return
	 */
	@AutoLog(value = "一厂一策管理-编辑")
	@ApiOperation(value="一厂一策管理-编辑", notes="一厂一策管理-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ControlStrategy controlStrategy) {
		Integer four=controlStrategy.getFourthStage();
		Integer five=controlStrategy.getFifthStage();
		Integer six=controlStrategy.getSixthStage();
		int num =four+five+six;
		if(num>100){
			return Result.error("总比例超过100");
		}
		controlStrategyService.updateById(controlStrategy);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "一厂一策管理-通过id删除")
	@ApiOperation(value="一厂一策管理-通过id删除", notes="一厂一策管理-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		controlStrategyService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "一厂一策管理-批量删除")
	@ApiOperation(value="一厂一策管理-批量删除", notes="一厂一策管理-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.controlStrategyService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "一厂一策管理-通过id查询")
	@ApiOperation(value="一厂一策管理-通过id查询", notes="一厂一策管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ControlStrategy controlStrategy = controlStrategyService.getById(id);
		if(controlStrategy==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(controlStrategy);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param controlStrategy
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ControlStrategy controlStrategy) {
        return super.exportXls(request, controlStrategy, ControlStrategy.class, "一厂一策管理");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ControlStrategy.class);
    }

}
